<template>
	<cl-page>
		<view class="page">
			<!-- 自定义状态栏 -->
			<cl-status-bar />

			<!-- 搜索栏 -->
			<cl-sticky>
				<view class="search-header">
					<view class="search-bar" @tap="toSearch">
						<view class="search-bar__inner">
							<cl-icon name="search" :margin="[0, 12, 0, 0]" color="#999"></cl-icon>
							<cl-text
								value="商品名称|生产厂家|商品助记码|通用名"
								color="#999"
								size="14"
							></cl-text>
						</view>
					</view>
					<view class="header-actions">
						<cl-icon name="bell" size="20" color="#333" @tap="toNotice"></cl-icon>
					</view>
				</view>
			</cl-sticky>

			<!-- 动态内容区域 -->
			<view class="content-wrapper">
				<!-- Banner轮播 -->
				<view class="banner-section">
					<enhanced-banner :banners="pageData.bannerList" @click="onBannerClick" />
				</view>

				<!-- 快捷导航 -->
				<view class="quick-nav-section">
					<quick-navigation />
				</view>

				<!-- 促销活动 -->
				<view class="promotion-section" v-if="promotionVisible">
					<promotion-banner :activities="pageData.promotionList" />
				</view>

				<!-- 品牌展示 -->
				<view class="brands-section" v-if="brandsVisible">
					<section-header title="品牌精选" subtitle="FEATURED BRANDS" @more="toBrands" />
					<brand-showcase :brands="pageData.brandList" />
				</view>

				<!-- 秒杀活动 -->
				<view class="flash-sale-section" v-if="flashSaleVisible">
					<flash-sale-banner :activity="pageData.flashSaleData" />
				</view>

				<!-- 商品推荐模块 -->
				<view class="product-sections">
					<!-- 热门推荐 -->
					<view class="product-section">
						<section-header
							title="热门推荐"
							subtitle="HOT PICKS"
							@more="toHotProducts"
						/>
						<view class="products-grid">
							<enhanced-goods-item
								v-for="item in hotProducts"
								:key="item.id"
								:item="item"
								@click="toGoodsDetail"
								@add-cart="addToCart"
								@collect="toggleCollect"
							/>
						</view>
					</view>

					<!-- 热销药品 -->
					<view class="product-section">
						<section-header
							title="热销药品"
							subtitle="BEST SELLERS"
							@more="toBestSellers"
						/>
						<hot-sales-products
							:products="bestSellerProducts"
							@add-cart="addToCart"
							@view-more="toBestSellers"
						/>
					</view>

					<!-- 新品上市 -->
					<view class="product-section">
						<section-header
							title="新品上市"
							subtitle="NEW ARRIVALS"
							@more="toNewProducts"
						/>
						<new-products-carousel :products="pageData.newProductsList" />
					</view>

					<!-- 分类推荐 -->
					<view
						class="category-products"
						v-for="category in pageData.categoryProducts"
						:key="category.id"
					>
						<section-header
							:title="category.name"
							:subtitle="category.subtitle"
							@more="toCategoryProducts(category.id)"
						/>
						<category-product-grid :products="category.products" :category="category" />
					</view>
				</view>

				<!-- 用户足迹 -->
				<view class="footprint-section" v-if="userStore.token && footprintVisible">
					<section-header
						title="浏览足迹"
						subtitle="BROWSING HISTORY"
						@more="toFootprint"
					/>
					<user-footprint :items="pageData.footprintList" />
				</view>

				<!-- 用户评价 -->
				<view class="reviews-section" v-if="reviewsVisible">
					<section-header title="用户评价" subtitle="USER REVIEWS" @more="toReviews" />
					<user-reviews-showcase :reviews="pageData.reviewsList" />
				</view>
			</view>

			<!-- 版本检查 -->
			<cl-version-upgrade :ref="setRefs('versionUpgrade')" />
		</view>

		<tabbar />
	</cl-page>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from "vue";
import { router, useCool, usePager } from "/@/cool";
import { onReady, onShareAppMessage, onReachBottom, onPullDownRefresh } from "@dcloudio/uni-app";
import { useStore } from "/@/cool/store";

// 组件导入
import Tabbar from "./components/tabbar.vue";
import EnhancedBanner from "./components/enhanced-banner.vue";
import QuickNavigation from "./components/quick-navigation.vue";
import PromotionBanner from "./components/promotion-banner.vue";
import SectionHeader from "./components/section-header.vue";
import BrandShowcase from "./components/brand-showcase.vue";
import FlashSaleBanner from "./components/flash-sale-banner.vue";
import EnhancedGoodsItem from "/@/components/goods/enhanced-item.vue";
import NewProductsCarousel from "./components/new-products-carousel.vue";
import HotSalesProducts from "./components/hot-sales-products.vue";
import CategoryProductGrid from "./components/category-product-grid.vue";
import UserFootprint from "./components/user-footprint.vue";
import UserReviewsShowcase from "./components/user-reviews-showcase.vue";

const { service, refs, setRefs } = useCool();
const { onRefresh, onData } = usePager();
const { user: userStore } = useStore();

// 页面数据
const pageData = reactive({
	bannerList: [] as any[],
	promotionList: [] as any[],
	brandList: [] as any[],
	flashSaleData: null as any,
	newProductsList: [] as any[],
	categoryProducts: [] as any[],
	footprintList: [] as any[],
	reviewsList: [] as any[],
	layoutConfig: [] as any[],
	cartCount: 0,
});

// 页面状态
const pageState = reactive({
	loading: false,
	refreshing: false,
	loadingMore: false,
});

// 显示控制
const bannerVisible = computed(() => pageData.bannerList?.length > 0);
const promotionVisible = computed(() => pageData.promotionList.length > 0);
const brandsVisible = computed(() => pageData.brandList.length > 0);
const flashSaleVisible = computed(() => !!pageData.flashSaleData);
const footprintVisible = computed(() => pageData.footprintList.length > 0);
const reviewsVisible = computed(() => pageData.reviewsList.length > 0);

// 商品数据
const hotProducts = ref<any[]>([]);
const bestSellerProducts = ref<any[]>([]);

// 获取热门推荐 (attribute: [3])
async function loadHotProducts() {
	try {
		const res = await service.goods.info.page({
			page: 1,
			size: 6,
			attribute: [3], // 热门推荐
			subTitle: "YES",
			order: "sortNum",
			sort: "desc",
		});

		hotProducts.value = res.list || [];
	} catch (error) {
		console.error("加载热门商品失败:", error);
	}
}

// 获取热销药品 (attribute: [2])
async function loadBestSellerProducts() {
	try {
		const res = await service.goods.info.page({
			page: 1,
			size: 6,
			attribute: [2], // 热销药品
			subTitle: "YES",
			order: "sortNum",
			sort: "desc",
		});

		bestSellerProducts.value = res.list || [];
	} catch (error) {
		console.error("加载热销药品失败:", error);
	}
}

// 获取新品上市 (attribute: [1])
async function loadNewProducts() {
	try {
		const res = await service.goods.info.page({
			page: 1,
			size: 10,
			attribute: [1], // 新品上市
			subTitle: "YES",
			order: "createTime",
			sort: "desc",
		});

		pageData.newProductsList = res.list || [];
	} catch (error) {
		console.error("加载新品上市失败:", error);
	}
}

// 初始化页面数据
async function initPageData() {
	try {
		pageState.loading = true;

		// 加载不需要登录的数据
		const [bannerRes, brandRes, layoutRes] = await Promise.all([
			service.info.banner.list(),
			service.brand.info.list(),
			service.app.layout.list(),
			loadHotProducts(), // 加载热门商品
			loadBestSellerProducts(), // 加载热销药品
			loadNewProducts(), // 加载新品上市
		]);

		// 处理Banner数据
		pageData.bannerList = bannerRes.filter((item) => item.type === 1) || [];

		// 处理品牌数据
		pageData.brandList = (brandRes || []).slice(0, 8);

		// 处理布局配置
		pageData.layoutConfig = layoutRes || [];

		// 加载需要登录的数据
		if (userStore.token) {
			const [promotionRes, flashSaleRes, reviewsRes] = await Promise.all([
				service.goods.promo.getActivePromos(),
				service.goods.promo.getByPromType({ promType: "SECKILL" }),
				service.goods.comment.page({ page: 1, size: 6 }),
			]);

			// 处理促销数据
			pageData.promotionList = promotionRes || [];

			// 处理秒杀数据
			pageData.flashSaleData = flashSaleRes?.[0] || null;

			// 处理评价数据
			pageData.reviewsList = reviewsRes?.list || [];

			// 加载用户相关数据
			await loadUserData();
		}
	} catch (error) {
		console.error("初始化页面数据失败:", error);
		uni.showToast({
			title: "加载失败",
			icon: "error",
		});
	} finally {
		pageState.loading = false;
	}
}

// 加载用户相关数据
async function loadUserData() {
	try {
		// 加载足迹
		const footprintRes = await service.user.footprint.page({ page: 1, size: 6 });
		pageData.footprintList = footprintRes?.list || [];
	} catch (error) {
		console.error("加载用户数据失败:", error);
	}
}

// 页面跳转方法
function toSearch() {
	router.push("/pages/goods/search");
}

function toNotice() {
	router.push("/pages/user/notice");
}

function toBrands() {
	router.push("/pages/goods/list?type=brand");
}

function toHotProducts() {
	router.push("/pages/goods/list?attribute=3");
}

function toBestSellers() {
	router.push("/pages/goods/list?attribute=2");
}

function toNewProducts() {
	router.push("/pages/goods/list?attribute=1");
}

function toCategoryProducts(categoryId: number) {
	router.push(`/pages/goods/list?categoryId=${categoryId}`);
}

function toFootprint() {
	router.push("/pages/user/footprint");
}

function toReviews() {
	router.push("/pages/goods/comment");
}

function toGoodsDetail(item: any) {
	router.push(`/pages/goods/detail?id=${item.id}`);
}

// 商品操作方法
async function addToCart(item: any) {
	if (!userStore.token) {
		router.push("/pages/user/login");
		return;
	}

	try {
		await service.order.cart.addCart({
			goodsId: item.goodsId,
			count: 1,
		});

		uni.showToast({
			title: "添加成功",
			icon: "success",
		});
	} catch (error) {
		uni.showToast({
			title: "添加失败",
			icon: "error",
		});
	}
}

async function toggleCollect(item: any) {
	if (!userStore.token) {
		router.push("/pages/user/login");
		return;
	}

	try {
		await service.user.collect.toggle({
			goodsId: item.id,
		});

		uni.showToast({
			title: item.isCollected ? "取消收藏" : "收藏成功",
			icon: "success",
		});

		item.isCollected = !item.isCollected;
	} catch (error) {
		uni.showToast({
			title: "操作失败",
			icon: "error",
		});
	}
}

// 事件处理
function onBannerClick(banner: any) {
	if (banner.path) {
		if (banner.path.startsWith("/")) {
			router.push(banner.path);
		} else {
			// 外部链接
			// #ifdef H5
			window.open(banner.path);
			// #endif
			// #ifndef H5
			uni.showToast({ title: "请在浏览器中打开", icon: "none" });
			// #endif
		}
	}
}

function loadMoreProducts() {
	// 可以在这里实现分页加载更多商品
	console.log("加载更多商品");
}

// 下拉刷新
onPullDownRefresh(async () => {
	pageState.refreshing = true;
	try {
		await initPageData();
	} finally {
		pageState.refreshing = false;
		uni.stopPullDownRefresh();
	}
});

// 上拉加载
onReachBottom(() => {
	if (!pageState.loadingMore) {
		loadMoreProducts();
	}
});

onReady(() => {
	initPageData();

	// #ifdef APP
	refs.versionUpgrade?.check();
	// #endif
});

onShareAppMessage(() => {
	return {
		title: "精选好药，品质保证",
		path: "/pages/index/home",
	};
});

defineExpose({
	refresh: initPageData,
	initPageData,
});
</script>

<style lang="scss" scoped>
.page {
	min-height: 100vh;
	background-color: #f5f5f5;

	.search-header {
		display: flex;
		align-items: center;
		padding: 20rpx 32rpx;
		background-color: #fff;

		.search-bar {
			flex: 1;
			margin-right: 24rpx;

			&__inner {
				display: flex;
				align-items: center;
				height: 72rpx;
				padding: 0 24rpx;
				background-color: #f5f5f5;
				border-radius: 36rpx;
			}
		}

		.header-actions {
			display: flex;
			align-items: center;
		}
	}

	.content-wrapper {
		padding: 24rpx;

		.banner-section {
			margin-bottom: 24rpx;
			border-radius: 24rpx;
			overflow: hidden;
			box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
		}

		.quick-nav-section {
			margin-bottom: 24rpx;
		}

		.promotion-section {
			margin-bottom: 24rpx;
		}

		.brands-section {
			margin-bottom: 24rpx;
			background-color: #fff;
			border-radius: 24rpx;
			padding: 24rpx;
			box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
		}

		.flash-sale-section {
			margin-bottom: 24rpx;
		}

		.product-sections {
			.product-section {
				margin-bottom: 24rpx;
				background-color: #fff;
				border-radius: 24rpx;
				padding: 24rpx;
				box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
			}
		}

		.footprint-section,
		.reviews-section {
			margin-bottom: 24rpx;
			background-color: #fff;
			border-radius: 24rpx;
			padding: 24rpx;
			box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
		}

		.more-products {
			padding: 24rpx 0;
			text-align: center;

			.load-more-trigger {
				display: inline-flex;
				align-items: center;
				padding: 16rpx 32rpx;
				background-color: #fff;
				border-radius: 32rpx;
				box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

				&:active {
					opacity: 0.7;
				}
			}
		}

		.products-grid {
			display: grid;
			grid-template-columns: repeat(2, 1fr);
			gap: 24rpx;
			background-color: #fff;
			border-radius: 24rpx;
		}
	}
}
</style>
